package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

/**
 * https://leetcode.cn/problems/balanced-binary-tree/description/
 * <p>
 * 给定一个二叉树，判断它是否是平衡二叉树
 */
public class _17LetCode110_平衡二叉树 {

    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1) {
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1) {
            return -1;
        }
        if (Math.abs(rightHeight - leftHeight) > 1) {
            return -1;
        }
        return Math.max(leftHeight,rightHeight)+1;
    }
}
